const Friend = require('../models/friendModel');
const User = require('../models/userModel');
const db = require('../config/db');

const addFriend = (req, res) => {
  const { userId } = req.params;
  const { friendId } = req.body;

  if (userId === friendId) {
    return res.status(400).json({ error: 'Cannot add yourself as friend' });
  }

  Friend.addFriend(userId, friendId, function(err) {
    if (err) {
      return res.status(400).json({ error: 'Already friends' });
    }
    res.status(201).json({ message: 'Friend added successfully' });
  });
};

const getFriends = (req, res) => {
  const { userId } = req.params;
  
  // 更新当前用户的最后活跃时间
  User.updateLastActive(userId, (err) => {
    if (err) {
      return res.status(500).json({ error: 'Database error' });
    }
    
    Friend.getFriends(userId, async (err, friends) => {
      if (err) {
        return res.status(500).json({ error: 'Database error' });
      }
      
      // 获取每个好友的在线状态
      const friendsWithStatus = await Promise.all(friends.map(async (friend) => {
        const status = await new Promise((resolve) => {
          User.getStatus(friend.id, (err, result) => {
            resolve(result ? result.status : 'offline');
          });
        });
        return { ...friend, status };
      }));
      
      res.json(friendsWithStatus);
    });
  });
};

const getRecentFriends = (req, res) => {
  const { userId } = req.params;
  
  // 更新当前用户的最后活跃时间
  User.updateLastActive(userId, (err) => {
    if (err) {
      return res.status(500).json({ error: 'Database error' });
    }
    
    db.all(
      `SELECT DISTINCT 
        CASE 
          WHEN sender_id = ? THEN receiver_id 
          ELSE sender_id 
        END AS friend_id,
        MAX(timestamp) AS last_message_time
       FROM messages
       WHERE (sender_id = ? OR receiver_id = ?)
       AND timestamp >= datetime('now', '-5 days')
       GROUP BY friend_id
       ORDER BY last_message_time DESC`,
      [userId, userId, userId],
      async (err, recentFriends) => {
        if (err) {
          return res.status(500).json({ error: 'Database error' });
        }
        
        // 获取每个好友的详细信息和未读消息数量
        const friendsWithLastMessage = await Promise.all(recentFriends.map(async (friend) => {
          const [friendInfo, lastMessage, unreadCount] = await Promise.all([
            new Promise((resolve) => {
              User.findById(friend.friend_id, (err, result) => {
                resolve(result);
              });
            }),
            new Promise((resolve) => {
              db.get(
                `SELECT * FROM messages 
                 WHERE (sender_id = ? AND receiver_id = ?)
                 OR (sender_id = ? AND receiver_id = ?)
                 ORDER BY timestamp DESC
                 LIMIT 1`,
                [userId, friend.friend_id, friend.friend_id, userId],
                (err, result) => {
                  resolve(result);
                }
              );
            }),
            new Promise((resolve) => {
              db.get(
                `SELECT COUNT(*) AS unreadCount FROM messages 
                 WHERE receiver_id = ? AND sender_id = ? AND is_read = FALSE`,
                [userId, friend.friend_id],
                (err, result) => {
                  resolve(result ? result.unreadCount : 0);
                }
              );
            })
          ]);
          
          return {
            id: friend.friend_id,
            username: friendInfo?.username,
            lastMessage: lastMessage?.message,
            lastMessageTime: lastMessage?.timestamp,
            unreadCount: unreadCount || 0
          };
        }));
        
        res.json(friendsWithLastMessage);
      }
    );
  });
};

module.exports = { addFriend, getFriends, getRecentFriends }; 